<template>
  <div>
    <Card shadow>
      <p slot="title">
        快捷查询
      </p>
      <Form :label-width="120">
        <Row>
          <Col span="4">
            <FormItem label="专家：">
              <Select v-model="condition.expertId" clearable filterable style="width: 100%">
                <Option v-for="item in doctors" v-if="item.isExpert === 1" :value="item.id" :key="item.id">{{ item.username }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="4">
            <FormItem label="医生：">
              <Select v-model="condition.doctorId" clearable filterable style="width: 100%">
                <Option v-for="item in doctors" v-if="item.isExpert === 0" :value="item.id" :key="item.id">{{ item.username }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="4">
            <FormItem label="护士：">
              <Select v-model="condition.nurseId" clearable filterable style="width: 100%">
                <Option v-for="item in nurses" :value="item.id" :key="item.id">{{ item.username }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="4">
            <FormItem label="预约时间：">
              <DatePicker v-model="condition.appointment" placeholder="请选择" format="yyyy-MM-dd" type="date" style="width: 100%"></DatePicker>
            </FormItem>
          </Col>
          <Col span="4">
            <FormItem label="处理方式：">
              <Select v-model="condition.process" clearable filterable style="width: 100%">
                <Option :value="1" :key="1">电话随访</Option>
                <Option :value="2" :key="2">预约到店</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="4">
            <FormItem label="预约类型：">
              <Select v-model="condition.type" clearable filterable style="width: 100%">
                <Option :value="1" :key="1">会员预约</Option>
                <Option :value="2" :key="2">非会员预约</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Card>
    <Card style="margin-top: 5px" shadow>
        <iview-table
            ref="table"
            :baseURL="queryModel.baseURL"
            :menuId="dataModel.menuId"
            :columns="dataModel.columns"
            :order="dataModel.order"
            :pageNumber="pageModel.pageNumber"
            :pageSize="pageModel.pageSize"
            :defaultFilters="queryModel.defaultFilters"
            v-on="{changeSelect:changeSelect,changeTotalSize:changeTotalSize,events:events}">
        </iview-table>
        <br>
        <iview-page
            :totalSize="pageModel.totalSize"
            :pageNumber="pageModel.pageNumber"
            :pageSize="pageModel.pageSize"
            :pageSizeOpts="pageModel.pageSizeOpts"
            v-on="{changePageNumber:changePageNumber,changePageSize:changePageSize}">
        </iview-page>
    </Card>
    <Modal v-model="showAdd" :closable='false' :mask-closable=true :width="600">
      <h3 slot="header" style="color:#2D8CF0">请填写以下信息</h3>
      <Form :model="formItem" :label-width="100">
        <Row>
          <Col span="20" offset="2">
            <FormItem label="专家：" prop="categoryId">
              <Select v-model="formItem.expertId" clearable filterable style="width: 100%" :label-in-value=true @on-change="changeExpert">
                <Option v-for="item in doctors" v-if="item.isExpert === 1" :value="item.id" :key="item.id">{{ item.username }}</Option>
              </Select>
            </FormItem>
            <FormItem label="医生：" prop="doctorId">
              <Select v-model="formItem.doctorId" clearable filterable style="width: 100%" :label-in-value=true @on-change="changeDoctor">
                <Option v-for="item in doctors" v-if="item.isExpert === 0" :value="item.id" :key="item.id">{{ item.username }}</Option>
              </Select>
            </FormItem>
            <FormItem label="护士：" prop="nurseId">
              <Select v-model="formItem.nurseId" clearable filterable style="width: 100%" :label-in-value=true @on-change="changeNurse">
                <Option v-for="item in nurses" :value="item.id" :key="item.id">{{ item.username }}</Option>
              </Select>
            </FormItem>
            <FormItem label="治疗项目：" prop="projectId">
              <Select v-model="formItem.projectId" clearable filterable style="width: 100%" :label-in-value=true @on-change="changeProject">
                <Option v-for="item in projects" :value="item.id" :key="item.id">{{ item.name }}</Option>
              </Select>
            </FormItem>
            <FormItem label="治疗设备：" prop="equipmentId">
              <Select v-model="formItem.equipmentId" clearable filterable style="width: 100%" :label-in-value=true @on-change="changeEquipment">
                <Option v-for="item in equipments" :value="item.id" :key="item.id">{{ item.name }}</Option>
              </Select>
            </FormItem>
            <FormItem label="治疗开始时间：" prop="categoryId">
              <Row>
                <Col span="11">
                  <DatePicker v-model="startDate1" style="width: 100%" clearable placement="top" @on-change="changeStartDate" format="yyyy-MM-dd" type="date" placeholder=""></DatePicker>
                </Col>
                <Col span="2" align="center">-</Col>
                <Col span="11">
                  <TimePicker v-model="startTime1" type="time" format="HH:mm" placeholder="" @on-change="changeStartTime"></TimePicker>
                </Col>
              </Row>
            </FormItem>
            <FormItem label="治疗结束时间：" prop="categoryId">
              <Row>
                <Col span="11">
                  <DatePicker v-model="endDate1" style="width: 100%" clearable placement="top" @on-change="changeEndDate" format="yyyy-MM-dd" type="date" placeholder=""></DatePicker>
                </Col>
                <Col span="2" align="center">-</Col>
                <Col span="11">
                  <TimePicker v-model="endTime1" type="time" format="HH:mm" placeholder="" @on-change="changeEndTime"></TimePicker>
                </Col>
              </Row>
            </FormItem>
            <FormItem label="备注：" prop="categoryId">
              <Input v-model="formItem.remark" type="textarea" :autosize="{minRows: 4,maxRows: 5}" placeholder=""></Input>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button type="info" size="large" @click="submitTask">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import iviewTable from '@/view/common/table/Table.vue';
import iviewPage from '@/view/common/page/Page.vue';
import expandRow from './ReservationExpand.vue';
export default {
    components: {
        iviewTable,
        iviewPage,
        expandRow
    },
    data () {
        return {
            baseURL: '/user/reservation',
            // 考勤
            attendanceURL: '/user/attendance',
            projectURL: '/user/project',
            equipmentURL: '/user/equipment',
            taskURL: '/user/treatment/task',
            selectRows: [],
            selectRow: {},
            healthcare: [],
            doctors: [],
            nurses: [],
            projects: [],
            equipments: [],
            showAdd: false,
            showAppointment: false,
            startDate: '',
            startTime: '',
            endDate: '',
            endTime: '',
            startDate1: '',
            startTime1: '',
            endDate1: '',
            endTime1: '',
            formItem: {
                id: '',
                reservationId: '',
                expertId: '',
                doctorId: '',
                doctorName: '',
                nurseId: '',
                nurseName: '',
                projectId: '',
                projectName: '',
                equipmentId: '',
                equipmentName: '',
                startTimeStr: '',
                endTimeStr: '',
                remark: ''
            },
            queryModel: {
                // 网关代理路径(必须)+资源路径(可选)
                baseURL: '/user/reservation',
                defaultFilters: [
                    {'field': 'record_type', 'value1': 0, 'operate': '=='},
                    {'field': 'status', 'value1': 5, 'operate': '!='}
                ]
            },
            dataModel: {
                menuId: 510,
                columns: [
                    {
                        type: 'expand',
                        width: 50,
                        render: (h, params) => {
                            return h(expandRow, {
                                props: {
                                    row: params.row
                                }
                            })
                        }
                    },{
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },{
                        title: '预约时间',
                        key: 'appointment',
                        type: 'date',
                        sortable: true,
                        width: 150
                    },{
                        title: '预约患者',
                        key: 'patientName',
                        sortable: true,
                        width: 120
                    },{
                        title: '病历号',
                        key: 'medicalNumber',
                        sortable: true,
                        width: 150
                    },{
                        title: '预约类型',
                        key: 'type',
                        sortable: true,
                        width: 120,
                        render: (h, params) => {
                            let color = ''
                            let temp = params.row.type
                            if (temp === 1) {
                                temp = '复诊预约'
                                color = '#2d8cf0'
                            } else if (temp === 2) {
                                temp = '新诊预约'
                                color = '#19be6b'
                            }
                            return h('Tag',{
                                props: {
                                    // type: 'border',
                                    color: color
                                }
                            }, temp)
                        }
                    },
                    {
                        title: '处理方式',
                        key: 'process',
                        sortable: true,
                        width: 150,
                        render: (h, params) => {
                            let color = ''
                            let temp = params.row.process
                            if (temp === 1) {
                                temp = '电话随访'
                                color = '#19be6b'
                            } else if (temp === 2) {
                                temp = '预约到店'
                                color = '#2d8cf0'
                            }
                            return h('Tag',{
                                props: {
                                    // type: 'border',
                                    color: color
                                }
                            }, temp)
                        }
                    },{
                        title: '预约专家',
                        key: 'expertName',
                        sortable: true,
                        width: 120
                    },{
                        title: '预约医生',
                        key: 'doctorName',
                        sortable: true,
                        width: 120
                    },{
                        title: '接待人',
                        key: 'nurseName',
                        sortable: true,
                        width: 120
                    },{
                        title: '预约备注',
                        key: 'note'
                    },{
                        title: '预约状态',
                        key: 'status',
                        sortable: true,
                        width: 120,
                        render: (h, params) => {
                            let color = ''
                            let temp = params.row.status
                            if (temp === 0) {
                                temp = '已预约'
                                color = 'green'
                            } else if (temp === 1) {
                                temp = '已回访'
                                color = 'blue'
                            } else if (temp === 2) {
                                temp = '已到场'
                                color = 'yellow'
                            } else if (temp === 3) {
                                temp = '已接诊'
                                color = 'red'
                            } else if (temp === 4) {
                                temp = '已完成'
                                color = '#19be6b'
                            } else if (temp === 5) {
                                temp = '已取消'
                                color = '#bbbec4'
                            } else if (temp === 6) {
                                temp = '已支持'
                                color = '#ff9900'
                            }
                            return h('Tag',{
                                props: {
                                    // type: 'border',
                                    color: color
                                }
                            }, temp)
                        }
                    }, {
                        title: '排班状态',
                        key: 'isSchedule',
                        sortable: true,
                        width: 120,
                        render: (h, params) => {
                            let color = ''
                            let temp = params.row.isSchedule
                            if (temp === 0) {
                                temp = '未排班'
                                color = '#19be6b'
                            } else if (temp === 1) {
                                temp = '已排班'
                                color = '#ed3f14'
                            }
                            return h('Tag',{
                                props: {
                                    // type: 'border',
                                    color: color
                                }
                            }, temp)
                        }
                    }
                ],
                order: 'appointment asc'
            },
            pageModel: {
                totalSize: 0,
                pageNumber: 1,
                pageSize: 100,
                pageSizeOpts: [10, 50, 100, 500]
            },
            condition: {
                type: '',
                process: '',
                appointment: '',
                doctorId: '',
                nurseId: ''
            }
        }
    },
    methods: {
        events (item) {
            if (item.path === 'change') {
                this.change()
            } else if (item.path === 'cancel'){
                this.cancel()
            } else if (item.path === 'addTask') {
                this.addTask()
            } else if (item.path === 'cancelTask') {
                this.cancelTask()
            } else if (item.path === 'delete') {
                this.delete()
            }
        },
        loadDoctor () {
            let url = '/user/findByJob/1'
            this.$ajax.get(url).then(r => {
                let {code, data, msg} = r.data
                if (code === 0) {
                    this.doctors = data
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        loadNurse () {
            let url = '/user/findByJob/2'
            this.$ajax.get(url).then(r => {
                let {code, data, msg} = r.data
                if (code === 0) {
                    this.nurses = data
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        change () {
            if (this.selectRows.length === 1) {
                let row = this.selectRows[0]
                let url = this.baseURL + '/checkChange/' + row.id
                this.$ajax.get(url).then(response => {
                    let {code, msg} = response.data
                    if (code === 0) {
                        this.$bus.toPath('/reservation/details', row)
                    } else {
                        this.$bus.alert('warning', msg)
                    }
                })
            } else {
                this.$bus.alert('warning', '请选择一条记录')
            }
        },
        changeExpert (option) {
            this.formItem.expertName = option.label
        },
        changeDoctor (option) {
            this.formItem.doctorName = option.label
        },
        changeNurse (option) {
            this.formItem.nurseName = option.label
        },
        changeProject (option) {
            this.formItem.projectName = option.label
        },
        changeEquipment (option) {
            this.formItem.equipmentName = option.label
        },
        changeStartDate (value, type) {
            this.startDate = value
        },
        changeStartTime (value, type) {
            this.startTime = value + ':00'
        },
        changeEndDate (value, type) {
            this.endDate = value
        },
        changeEndTime (value, type) {
            this.endTime = value + ':00'
        },
        delete () {
            if (this.selectRows.length > 0) {
                let ids = []
                for (let row of this.selectRows) {
                    ids.push(row.id)
                }
                let url = this.baseURL + '/checkDelete'
                this.$ajax.post(url, ids).then((response) => {
                    let {code, data} = response.data
                    if (code === 0) {
                        if (data.length > 0) {
                            this.$Modal.confirm({
                                title: '操作提示',
                                content: '<p>可以删除'+data.length+'条记录，确认删除?</p>',
                                onOk: () => {
                                    this.doDelete(data)
                                }
                            })
                        } else {
                            this.$bus.alert("warning", "没有符合条件的记录")
                        }
                    }
                })
            } else {
                this.$bus.alert('warning', '请至少选择一条记录')
            }
        },
        doDelete (ids) {
            let url = this.baseURL + '/delete'
            this.$ajax.post(url, ids).then((response) => {
                let {code, msg} = response.data
                if (code === 0) {
                    this.$bus.alert('success', '删除成功')
                    this.refresh()
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        cancel () {
            if (this.selectRows.length  === 1) {
                let id = this.selectRows[0].id
                let url = this.baseURL + '/checkCancel/' + id
                this.$ajax.get(url).then((response) => {
                    let {code, data, msg} = response.data
                    if (code === 0) {
                        if (data) {
                            this.$Modal.confirm({
                                title: '操作提示',
                                content: '<p>确认取消预约?</p>',
                                onOk: () => {
                                    this.doCancel(id)
                                }
                            })
                        } else {
                            this.$bus.alert('warning', '该记录不符合条件')
                        }
                    } else {
                        this.$bus.alert('error', msg)
                    }
                });
            } else {
                this.$bus.alert('warning', '请选择一条记录')
            }
        },
        doCancel (id) {
            let url = this.baseURL + '/cancel/' + id
            this.$ajax.post(url).then((response) => {
                let {code, msg} = response.data
                if (code === 0) {
                    this.$bus.alert('success', '取消成功')
                    this.refresh()
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        loadProject () {
            let url = this.projectURL + '/findAll'
            this.$ajax1.get(url).then(r => {
                let {code, data, msg} = r.data
                if (code === 0) {
                    this.projects = data
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        loadEquipment () {
           let url = this.equipmentURL + '/findAll'
           this.$ajax1.get(url).then(r => {
               let {code, data, msg} = r.data
               if (code === 0) {
                   this.equipments = data
               } else {
                   this.$bus.alert('error', msg)
               }
           })
        },
        addTask () {
            if (this.selectRows.length === 1) {
                this.selectRow = this.selectRows[0]
                if (this.selectRow.isSchedule === 0) {
                    // 加载治疗项目
                    this.loadProject()
                    // 加载医疗设备
                    this.loadEquipment()
                    this.$bus.init(this.formItem)
                    setTimeout(() => {
                        // 默认带出
                        if (this.selectRow.expertId) {
                            this.formItem.expertId = parseInt(this.selectRow.expertId)
                            this.formItem.expertName = this.selectRow.expertName
                        }
                        this.formItem.doctorId = parseInt(this.selectRow.doctorId)
                        this.formItem.nurseId = parseInt(this.selectRow.nurseId)
                        this.startDate1 = ''
                        this.startTime1 = ''
                        this.endDate1 = ''
                        this.endTime1 = ''
                        this.showAdd = true
                    }, 50)
                } else {
                    this.$bus.alert('warning', '请不要重复排班')
                }
            } else {
                this.$bus.alert('warning', '请选择一条记录')
            }
        },
        submitTask () {
            if (this.startDate === '') {
                this.$bus.alert('warning', '请选择治疗开始日期')
                return
            }
            if (this.startTime === '') {
                this.$bus.alert('warning', '请选择治疗开始时间')
                return
            }
            if (this.endDate === '') {
                this.$bus.alert('warning', '请选择治疗结束日期')
                return
            }
            if (this.endTime === '') {
                this.$bus.alert('warning', '请选择治疗结束时间')
                return
            }
            // 预约主键
            this.formItem.reservationId = this.selectRow.id
            // 患者主键
            this.formItem.patientId = this.selectRow.patientId
            // 患者名称
            this.formItem.patientName = this.selectRow.patientName
            this.formItem.medicalNumber = this.selectRow.medicalNumber
            this.formItem.startTimeStr = this.startDate + ' ' + this.startTime
            this.formItem.endTimeStr = this.endDate + ' ' + this.endTime
            let url = this.taskURL + '/save'
            this.$ajax.post(url, this.formItem).then(r => {
                let {code, msg} = r.data
                if (code === 0) {
                    this.showAdd = false
                    this.$bus.alert('success', '提交成功')
                    this.refresh()
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        cancelTask () {
            if (this.selectRows.length > 0) {
                let ids = []
                for (let row of this.selectRows) {
                    ids.push(row.id)
                }
                this.$Modal.confirm({
                    title: '操作提示',
                    content: '<p>确认取消'+ids.length+'条记录的排班</p>',
                    onOk: () => {
                        this.doCancelTask(ids)
                    }
                })
            } else {
                this.$bus.alert('warning', '请至少选择一条记录')
            }
        },
        doCancelTask (ids) {
            let url = this.taskURL + '/cancel'
            this.$ajax.post(url, ids).then(r => {
                let {code, msg} = r.data
                if (code === 0) {
                    this.$bus.alert('success', '取消成功')
                    this.refresh()
                } else {
                    this.$bus.alert('error', msg)
                }
            })
        },
        refresh () {
            this.$refs.table.refresh()
        },
        changeSelect (selection) {
            this.selectRows = selection
        },
        changeTotalSize (totalSize) {
            this.pageModel.totalSize = totalSize
        },
        changePageNumber (pageNumber) {
            this.pageModel.pageNumber = pageNumber
        },
        changePageSize (pageSize) {
            this.pageModel.pageSize = pageSize
        },
        init () {
            this.loadDoctor()
            this.loadNurse()
            this.refresh()
        },
        search () {
            this.pageModel.pageNumber = 1
            this.queryModel.defaultFilters.length = 0
            this.queryModel.defaultFilters.push({'field': 'record_type', 'value1': 0, 'operate': '=='})
            this.queryModel.defaultFilters.push({'field': 'status', 'value1': 5, 'operate': '!='})
            if (this.condition.type && this.condition.type !== '') {
                this.queryModel.defaultFilters.push({'field': 'type', 'value1': this.condition.type, 'operate': '=='})
            }
            if (this.condition.process && this.condition.process !== '') {
                this.queryModel.defaultFilters.push({'field': 'process', 'value1': this.condition.process, 'operate': '=='})
            }
            if (this.condition.expertId && this.condition.expertId !== '') {
                this.queryModel.defaultFilters.push({'field': 'expert_id', 'value1': this.condition.expertId, 'operate': '=='})
            }
            if (this.condition.doctorId && this.condition.doctorId !== '') {
                this.queryModel.defaultFilters.push({'field': 'doctor_id', 'value1': this.condition.doctorId, 'operate': '=='})
            }
            if (this.condition.nurseId && this.condition.nurseId !== '') {
                this.queryModel.defaultFilters.push({'field': 'nurse_id', 'value1': this.condition.nurseId, 'operate': '=='})
            }
            if (this.condition.appointment && this.condition.appointment !== '') {
                this.queryModel.defaultFilters.push({'field': 'appointment', 'value1': this.$moment(this.condition.appointment).format("YYYY-MM-DD") + ' 00:00:00', 'operate': '>='})
                this.queryModel.defaultFilters.push({'field': 'appointment', 'value1': this.$moment(this.condition.appointment).format("YYYY-MM-DD") + ' 23:59:59', 'operate': '<='})
            }
            this.refresh()
        }
    },
    mounted () {
        this.init()
    },
    watch: {
        '$route' (to) {
            if (to.path === '/reservation/list') {
                this.init()
            }
        },
        'condition.type': function (val, oldValue) {
            this.search()
        },
        'condition.process': function (val, oldValue) {
            this.search()
        },
        'condition.expertId': function (val, oldValue) {
            this.search()
        },
        'condition.doctorId': function (val, oldValue) {
            this.search()
        },
        'condition.nurseId': function (val, oldValue) {
            this.search()
        },
        'condition.appointment': function (val, oldValue) {
            this.search()
        }
    }
}
</script>

<style>

</style>
